package cn.relx.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Component
public class LoginCheckFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        // 1.从请求头中获取token，此处获取到的是一个集合
        log.info("Access Path:{}",path);
        if(!path.endsWith("login") && !path.endsWith("register")){
            List<String> token = exchange.getRequest().getHeaders().get("token");
            if(token == null || token.size() == 0){
                ServerHttpResponse response = exchange.getResponse();
                HashMap<String,Object> map = new HashMap<>();
                map.put("code",401);
                map.put("success",false);
                map.put("message","登录验证失败，请重新登录!");
                DataBuffer buffer = null;
                try {
                    byte[] bytes = JSON.toJSONString(map).getBytes("Utf-8");
                    buffer = response.bufferFactory().wrap(bytes);
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return response.writeWith(Mono.just(buffer));
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
